#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<string>
#include<string.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
using namespace std;

const int MaxSize=1024;

char * UsrName;
char * HostName;
char  CommandPwd[MaxSize];

//打印命令行提示符
void PrintCLPrompt()
{
    printf("[%s@%s %s]@",UsrName,HostName,CommandPwd);
}

//准备工作
void setup()
{
    UsrName=getenv("USER");
    HostName=getenv("HOSTNAME");
    
    string str=getenv("PWD");
    string tmp=str.substr(str.rfind("/")+1);//加一去除/字符
    snprintf(CommandPwd,MaxSize,"%s",tmp.c_str());//格式化输出到数组函数
}

//读取处理指令
char Command[MaxSize];
char * argv[MaxSize];
void ReadDealCommand()
{
    //读取一行字符串
    fgets(Command,MaxSize,stdin);

    int len=strlen(Command)-1;//fegts会把\n也读取到，但这个是不用的字符
    Command[len]='\0';
    //处理字符串
    int size=0;
    int prev=-1,cur=0;

    //预处理，将空格换成\0
    for(int i=0; i<len; i++)
    {
        if(Command[i]==' ')
            Command[i]='\0';
    }

    while(cur<len)
    {
        if(prev == -1 && Command[cur]!='\0'
                || Command[prev]=='\0' && Command[cur]!='\0')
        {
            argv[size++]=Command+cur;
           //.autorelabel printf("%d ",cur);
        }

        prev++;
        cur++;
    }
    
    //argv最后加上NULL
    argv[size]=NULL;

}
//执行指令
void PreformCommand()
{
    //bash内部程序
    if(strcmp("pwd",argv[0])==0)
    { 
        printf("%s\n",getenv("PWD"));
        return ;
    }
    else if(strcmp("cd",argv[0])==0)
    {
        chdir(argv[1]);

        char cwd[1024];
        getcwd(cwd,1024);
        //更新地址
        string str=cwd;
        string tmp=str.substr(str.rfind("/")+1);//加一去除/字符
        snprintf(CommandPwd,MaxSize,"%s",tmp.c_str());//格式化输出到数组函数
        
        //修改环境变量
        string s="PWD=";
        s+=cwd;
        snprintf(cwd,MaxSize,"%s",s.c_str());//格式化输出到数组函数 
        putenv(cwd);//putenv参数要是char*，但c_str()返回的是const char *
        

        return ;
    }
    

    pid_t id=fork();

    if(id ==0 )
    {
        execvp(argv[0],argv);
       
        //切换不成功返回退出码
        exit(111);
    }

    //父进程
    int status=0;
    pid_t rid=wait(&status);
     if (WIFEXITED(status))
     {
         // 子进程正常退出，提取退出状态码
         int exit_status = WEXITSTATUS(status);
        // printf("Child process exited normally with status %d\n", exit_status);
     }
     else if (WIFSIGNALED(status)) {
            // 子进程因信号终止，提取信号编号
            int signal_num = WTERMSIG(status);
            printf("Child process terminated by signal %d\n", signal_num);
    }    
}


int main()
{
    
    setup();

    while(1)
    {   
        //打印提示行
        PrintCLPrompt();

        //读取处理指令
        ReadDealCommand();
        
        //执行指令
        PreformCommand();
    }


    return 0;
}
